package com.sfh.cp.widget.refresh;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sfh.cp.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述:刷新加载更多控件
 *
 * @author SunFeihu 孙飞虎
 * @date 2017/7/12
 */
public class SwipeRefreshMoreLayout extends FrameLayout implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    /**
     * 刷新控件
     */
    protected SwipeRefreshLayout mSwipeRefreshLayout;
    /**
     * 视图显示控件
     */
    protected RecyclerView mRecyclerView;
    /**
     * 适配器
     */
    protected BaseQuickAdapter pullToRefreshAdapter;
    /**
     * 加载更多与刷新回调
     */
    protected OnLoadingListener mListener;
    /**
     * 延迟刷新时间【毫秒】
     */
    protected long time = 250L;


    /**
     * 无数据对象
     */
    protected int emptyLayout = R.layout.refresh_empty_view;

    /**
     * 无数据对象View
     */
    protected View emptyView;

    public SwipeRefreshMoreLayout(@NonNull Context context) {

        super(context);
        this.init();
    }

    public SwipeRefreshMoreLayout(@NonNull Context context, @Nullable AttributeSet attrs) {

        super(context, attrs);
        this.init();
    }

    public SwipeRefreshMoreLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {

        super(context, attrs, defStyleAttr);
        this.init();
    }

    public SwipeRefreshMoreLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {

        super(context, attrs, defStyleAttr);
        this.init();
    }

    public interface OnLoadingListener {

        /***刷新*/
        void onRefreshUI();

        /***加载更多*/
        void onLoadMoreUI();
    }


    private void init() {

        inflate(getContext(), R.layout.refresh_more_layout, this);
        this.mSwipeRefreshLayout = $(R.id.base_refresh);
        this.mRecyclerView = $(R.id.base_list);
    }

    /***
     * 设置适配器
     * @param adapter
     * @param loadMore true 表示刷新+加载更多 false 只有刷新功能
     */
    public void setAdapter(BaseQuickAdapter adapter, boolean loadMore) {

        if (adapter == null) {
            return;
        }
        this.pullToRefreshAdapter = adapter;

        this.mSwipeRefreshLayout.setColorSchemeColors(Color.parseColor("#3c75ed"));
        // 刷新
        this.mSwipeRefreshLayout.setOnRefreshListener(this);
        //线性
        this.mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getContext()));
        // 加载动画
        this.pullToRefreshAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        // 先绑定RecyclerView
        this.pullToRefreshAdapter.bindToRecyclerView(mRecyclerView);

        if (loadMore) {
            // 加载更多
            this.pullToRefreshAdapter.setOnLoadMoreListener(this, mRecyclerView);
            // 默认不加载更多
            this.pullToRefreshAdapter.disableLoadMoreIfNotFullPage();
            //自定义加载布局
            this.pullToRefreshAdapter.setLoadMoreView(new CustomLoadMoreView());
        }
    }

    /***
     * 设置Iitem 项间距
     * @param dimen 资源ID
     */
    public void addItemDecorationSize(@DimenRes final int dimen) {
        if (this.mRecyclerView == null) {
            return;
        }
        int top = getResources().getDimensionPixelOffset(dimen);
        this.mRecyclerView.addItemDecoration(new SpaceItemDecoration(top));
    }

    /***
     * 设置Iitem 分割线
     */
    public void addItemDecoration(@DrawableRes int drawable, int insetLeft, int insetRight) {

        if (this.mRecyclerView == null) {
            return;
        }
        this.mRecyclerView.addItemDecoration( new CustomDecoration(drawable, insetLeft, insetRight));
    }
    /***
     * 设置Iitem 分割线
     */
    public void addItemDecoration(@DrawableRes int drawable) {

        if (this.mRecyclerView == null) {
            return;
        }
        this.mRecyclerView.addItemDecoration( new CustomDecoration(drawable, 0, 0));
    }
    /***
     * 【先绑定适配器】
     * 设置无数据时空白页，默认R.layout.base_list_empty_view
     */
    public void setEmptyView(int layout) {

        if (this.pullToRefreshAdapter == null) {
            return;
        }
        this.emptyLayout = layout;
    }

    /***
     * 【先绑定适配器】
     * 设置无数据时空白页，默认R.layout.base_list_empty_view
     */
    public void setEmptyView(View emptyView) {

        if (this.pullToRefreshAdapter == null) {
            return;
        }
        this.emptyView = emptyView;
    }


    /***
     * 设置内容边距 已存在默认值@dimen/x10
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setPaddingContent(int left, int top, int right, int bottom) {

        if (this.mRecyclerView == null) {
            return;
        }
        this.mRecyclerView.setPadding(left, top, right, bottom);
    }

    /***
     * 设置RecyclerView 布局模式【默认线性】
     */
    public void setLayoutManager(RecyclerView.LayoutManager layout) {
        if (this.mRecyclerView == null) {
            return;
        }
        //线性
        this.mRecyclerView.setLayoutManager(layout);
    }


    private <T extends View> T $(@IdRes int resId) {

        return (T) super.findViewById(resId);
    }

    @Override
    public void onRefresh() {
        if (this.pullToRefreshAdapter == null) {
            return;
        }
        this.pullToRefreshAdapter.setEnableLoadMore(false);
        if (this.mListener != null) {
            this.mListener.onRefreshUI();
        }
    }

    @Override
    public void onLoadMoreRequested() {

        if (this.mListener != null) {
            this.mListener.onLoadMoreUI();
        }
    }

    /****
     * 刷新+加载更多回调
     * @param mListener
     */
    public void setOnLoadingListener(OnLoadingListener mListener) {

        this.mListener = mListener;
    }

    /***
     * item view 中控件点击事件
     * @param listener
     */
    public void setOnItemChildClickListener(BaseQuickAdapter.OnItemChildClickListener listener) {
        if (this.pullToRefreshAdapter == null) {
            return;
        }
        //子控件点击事件
        this.pullToRefreshAdapter.setOnItemChildClickListener(listener);
    }

    /*** item 点击事件 */
    public void setOnItemClickListener(@Nullable BaseQuickAdapter.OnItemClickListener listener) {
        if (this.pullToRefreshAdapter == null) {
            return;
        }
        //Item 点击事件
        this.pullToRefreshAdapter.setOnItemClickListener(listener);
    }

    /***
     * 是否全部加载完成 【外部调用】
     */
    public void onLoadAllCompale() {
        if (this.pullToRefreshAdapter == null) {
            return;
        }
        this.pullToRefreshAdapter.loadMoreEnd();
        this.closeRefresh();
        this.showEmptyView();
    }


    /***
     * 获取更多数据失败 【外部调用】
     *
     */
    public void onLoadMoreFail() {
        if (this.pullToRefreshAdapter == null) {
            return;
        }
        this.pullToRefreshAdapter.loadMoreFail();
        this.closeRefresh();
        this.showEmptyView();
    }

    /***
     * 完成数据加载【外部调用】
     *
     * @param data 数据
     * @param loadMore true 加载更多完成 false 刷新完成
     */
    public void onRefreshCompale(final List data, boolean loadMore) {
        if (this.pullToRefreshAdapter == null) {
            return;
        }

        List temp = data == null ? new ArrayList(0) : data;

        if (loadMore) {
            //成功获取更多数据
            this.pullToRefreshAdapter.addData(temp);
            this.pullToRefreshAdapter.loadMoreComplete();
        } else {

            this.pullToRefreshAdapter.setNewData(temp);
            this.pullToRefreshAdapter.setEnableLoadMore(true);
            this.closeRefresh();
            this.showEmptyView();
        }

    }

    // 关闭刷新
    private void closeRefresh() {

        this.postDelayed(new Runnable() {

            @Override
            public void run() {

                SwipeRefreshMoreLayout.this.removeCallbacks(this);
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        }, time);
    }

    /***
     * 数据为空
     */
    private void showEmptyView() {
        if (this.pullToRefreshAdapter == null) {
            return;
        }
        List data = this.pullToRefreshAdapter.getData();
        if (data == null || data.isEmpty()) {
            View emptyViewiew = this.pullToRefreshAdapter.getEmptyView();
            if (emptyViewiew == null) {
                if (this.emptyView == null) {
                    this.pullToRefreshAdapter.setEmptyView(this.emptyLayout);
                } else {
                    this.pullToRefreshAdapter.setEmptyView(this.emptyView);
                }
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {

        this.removeCallbacks(null);
        super.onDetachedFromWindow();
    }

    /****
     * 自动刷新【外部调用】
     */
    public void onAutoRefresh() {

        // 已正在刷新
        if (mSwipeRefreshLayout.isRefreshing()) {
            return;
        }

        this.postDelayed(new Runnable() {

            @Override
            public void run() {

                SwipeRefreshMoreLayout.this.removeCallbacks(this);
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(true);
                }
                if (mListener != null) {
                    mListener.onRefreshUI();
                }
            }
        }, time);
    }

    /***
     * 禁止下拉刷新
     * @param enabled
     */
    public void setForbidRefreshLayout(boolean enabled) {
        this.mSwipeRefreshLayout.setEnabled(enabled);
    }

    /***
     * 项间距
     */
    public static class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        public void setSpace(int space) {

            this.space = space;
        }

        private int space;

        public SpaceItemDecoration(int space) {

            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            if (parent.getChildLayoutPosition(view) != 0) {
                outRect.top = space;
            }
        }
    }

    class CustomDecoration extends RecyclerView.ItemDecoration {


        private Drawable mDivider;

        /**
         * 分割线缩进值
         */
        private int insetLeft;
        private int insetRight;

        private Paint paint;

        /**
         * @param drawable 引入的drawable的ID
         */
        public CustomDecoration(int drawable, int insetLeft, int insetRight) {

            this.mDivider = ContextCompat.getDrawable(getContext(), drawable);
            this.insetLeft = insetLeft;
            this.insetRight = insetRight;

            this.paint = new Paint();
            this.paint.setColor(Color.WHITE);
            this.paint.setStyle(Paint.Style.FILL);
            this.paint.setAntiAlias(true);
        }


        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

            final int left = parent.getPaddingLeft();
            final int right = parent.getWidth() - parent.getPaddingRight();

            final int childCount = parent.getChildCount();
            //最后一个item不画分割线
            for (int i = 0; i < childCount - 1; i++) {
                final View child = parent.getChildAt(i);
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();
                if (this.insetLeft > 0 || this.insetRight > 0) {
                    c.drawRect(left, top, right, bottom, paint);
                }
                mDivider.setBounds(left + this.insetLeft, top, right - this.insetRight, bottom);
                mDivider.draw(c);
            }
        }

        //由于Divider也有宽高，每一个Item需要向下或者向右偏移
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if (parent.getChildLayoutPosition(view) != 0) {
                outRect.top = mDivider.getIntrinsicHeight();
            }
        }
    }


    /***
     * 处理异常 Inconsistency detected. Invalid item position异常
     */
    public static class WrapContentLinearLayoutManager extends LinearLayoutManager {

        public WrapContentLinearLayoutManager(Context context) {
            super(context);
        }

        public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
}
